<?php defined('BASEPATH') OR exit('No direct script access allowed');


include_once(APPPATH.'libraries/MarketplaceWebServiceOrders/Client.php');
include_once(APPPATH.'libraries/MarketplaceWebServiceOrders/Model/ListOrdersRequest.php');
include_once(APPPATH.'libraries/MarketplaceWebServiceOrders/Model/ListOrderItemsRequest.php');
include_once(APPPATH.'libraries/MarketplaceWebServiceOrders/Model/ListOrdersByNextTokenRequest.php');
include_once(APPPATH.'libraries/MarketplaceWebServiceOrders/Exception.php');

require APPPATH.'/libraries/REST_Controller.php';

class Orders extends REST_Controller
{
	private $service;
	public $request;
	public $next_by_token = FALSE;

	function __construct()
	{
		// Construct our parent class
		parent::__construct();

		$serviceUrl = '';
		switch ($this->_merchant['region'])
		{
			case 'NA':
				$serviceUrl = "https://mws.amazonservices.com/Orders/2013-09-01";
				break;

			case 'CA':
				$serviceUrl = "https://mws.amazonservices.ca/Orders/2013-09-01";
				break;

			case 'DE':
				$serviceUrl = "https://mws.amazonservices.de/Orders/2013-09-01";
				break;

			case 'FR':
				$serviceUrl = "https://mws.amazonservices.fr/Orders/2013-09-01";
				break;

			case 'IT':
				$serviceUrl = "https://mws.amazonservices.it/Orders/2013-09-01";
				break;

			case 'UK':
				$serviceUrl = "https://mws.amazonservices.co.uk/Orders/2013-09-01";
				break;

			case 'JP':
				$serviceUrl = "https://mws.amazonservices.com.cn/Orders/2013-09-01";
				break;

			case 'CN':
				$serviceUrl = "https://mws.amazonservices.com.cn/Orders/2013-09-01";
				break;

			default:
				$serviceUrl = "https://mws.amazonservices.com/Orders/2013-09-01";
			break;
		}

		$this->service = new MarketplaceWebServiceOrders_Client(
		AWS_ACCESS_KEY_ID,
		AWS_SECRET_ACCESS_KEY,
		APPLICATION_NAME,
		APPLICATION_VERSION,
		array (
                'ServiceURL' => $serviceUrl,
                'ProxyHost' => null,
                'ProxyPort' => -1,
                'MaxErrorRetry' => 3
		)
		);

		$tmp = $this->input->get('next_by_token');
		if($tmp)
		{
			$this->next_by_token = ((int)$tmp)?TRUE:FALSE;
		}

	}

	function getOrderDetails_get()
	{

		//include required libraries
		include_once(APPPATH.'libraries/MarketplaceWebServiceOrders/Model/GetOrderRequest.php');

		//create object of order request
		$this->request = new MarketplaceWebServiceOrders_Model_GetOrderRequest();
		//set SELLER ID
		$this->request->setSellerId(MERCHANT_ID);

		$params = array('AmazonOrderId' => array('type' => 'array'));
		$this->amazon_mws->set_request( $params, 'get');

		$this->invokeGetOrder($this->service, $this->request);

	}

	function listOrders_get()
	{
		//create object of order request
		$this->request = new MarketplaceWebServiceOrders_Model_ListOrdersRequest();
		$this->request->setSellerId(MERCHANT_ID);

		$params = array(
                    'CreatedAfter' => array('type' => 'date'),
                    'CreatedBefore' => array('type' => 'date'),
                    'LastUpdatedAfter' => array('type' => 'date'),
                    'LastUpdatedBefore' => array('type' => 'date'),
                    'OrderStatus' => array('type' => 'array'),
                    'MarketplaceId' => array('type' => 'array'),
                    'FulfillmentChannel' => array('type' => 'array'),
                    'PaymentMethod' => array('type' => 'array'),
                    'BuyerEmail' => array('type' => 'string'),
                    'TFMShipmentStatus' => array('type' => 'array'),
                    'MaxResultsPerPage' => array('type' => 'string')
		);

		$this->amazon_mws->set_request( $params, 'get');


		if( !$this->request->issetMarketplaceId() )
		$this->request->setMarketplaceId(array(MARKETPLACE_ID));

		$this->invokeListOrders($this->service, $this->request);

	}

	function listOrdersByNextToken_get()
	{
		//create object of order request
		$this->request = new MarketplaceWebServiceOrders_Model_ListOrdersByNextTokenRequest();
		$this->request->setSellerId(MERCHANT_ID);

		$params = array(
                        'NextToken' => array('type' => 'string')
		);

		$this->amazon_mws->set_request( $params, 'get');
		 

		$this->invokeListOrders($this->service, $this->request, 'next_token');

	}


	//get order items list by id
	function getOrderItems_get()
	{

		$this->request = new MarketplaceWebServiceOrders_Model_ListOrderItemsRequest();
		$this->request->setSellerId(MERCHANT_ID);

		$params = array('AmazonOrderId' => array('type' => 'string'));
		$this->amazon_mws->set_request( $params, 'get');

		$this->invokeListOrderItems($this->service, $this->request);


	}

	//get order items list by id
	function getOrderItemsByNextToken_get()
	{

		$this->request = new MarketplaceWebServiceOrders_Model_ListOrderItemsByNextTokenRequest();
		$this->request->setSellerId(MERCHANT_ID);

		$params = array('NextToken' => array('type' => 'string'));
		$this->amazon_mws->set_request( $params, 'get');

		$this->invokeListOrderItems($this->service, $this->request, 'next_token');


	}


	function invokeGetOrder(MarketplaceWebServiceOrders_Interface $service, $request)
	{
		try
		{
			$response = $service->GetOrder($request);

			$this->amazon_mws->format_output($response, 'GetOrderResult|Orders|Order', 'Orders');

			$this->amazon_mws->show_ouput(TRUE);


		} catch (MarketplaceWebServiceOrders_Exception $ex)
		{
			$this->amazon_mws->format_error($ex->getXML());
			$this->amazon_mws->show_ouput(FALSE);
		}
	}




	function invokeListOrders(MarketplaceWebServiceOrders_Interface $service, $request, $type = null)
	{

		try
		{

			$listOrders             = "ListOrders";
			$isSetListOrdersResult  = "isSetListOrdersResult";
			$getListOrdersResult    = "getListOrdersResult";

			if(strcmp($type, 'next_token') === 0 )
			{
				$listOrders             = "ListOrdersByNextToken";
				$isSetListOrdersResult  = "isSetListOrdersByNextTokenResult";
				$getListOrdersResult    = "getListOrdersByNextTokenResult";
			}

			$response = $service->$listOrders($request);

			$this->amazon_mws->format_output($response, $listOrders.'Result|Orders|Order', 'Orders');


			//Get Next Token to fetch the next records in Queue
			$next_token = '';

			if ($response->$isSetListOrdersResult() )
			{
				$listOrdersResult = $response->$getListOrdersResult();

				if ($listOrdersResult->isSetNextToken())
				{
					$next_token = $listOrdersResult->getNextToken();
				}

			}

			$this->amazon_mws->next_token = $next_token;

			if( strcmp($next_token,'') !== 0  && $this->next_by_token)
			{
				$this->request = new MarketplaceWebServiceOrders_Model_ListOrdersByNextTokenRequest();
				$this->request->setSellerId(MERCHANT_ID);
				$this->request->setNextToken($next_token);

				$this->invokeListOrders($this->service, $this->request, 'next_token');
			}
			else
			{
				$this->amazon_mws->show_ouput(TRUE);
			}
			 
			return true;
		}
		catch (MarketplaceWebServiceOrders_Exception $ex)
		{
			$this->amazon_mws->format_error($ex->getXML());
			$this->amazon_mws->show_ouput(FALSE);
		}
	}



	function invokeListOrderItems(MarketplaceWebServiceOrders_Interface $service, $request, $type = null)
	{
		try
		{
			$listOrderItems             = "ListOrderItems";
			$isSetListOrderItemsResult  = "isSetListOrderItemsResult";
			$getListOrderItemsResult    = "getListOrderItemsResult";

			if(strcmp($type, 'next_token') === 0 )
			{
				$listOrderItems                 = "ListOrderItemsByNextToken";
				$isSetListOrderItemsResult  = "isSetListOrderItemsByNextTokenResult";
				$getListOrderItemsResult    = "getListOrderItemsByNextTokenResult";
			}

			$response = $service->listOrderItems($request);

			$this->amazon_mws->format_output($response, $listOrderItems.'Result|OrderItems|OrderItem', 'OrderItems');

			$next_token = '';

			if ($response->isSetListOrderItemsResult())
			{
				$listOrderItemsResult = $response->getListOrderItemsResult();

				if ($listOrderItemsResult->isSetNextToken())
				$next_token = $listOrderItemsResult->getNextToken();
				 
			}

			$this->amazon_mws->next_token = $next_token;

			if($next_token != '' && $this->next_by_token)
			{
				$this->request = new MarketplaceWebServiceOrders_Model_ListOrderItemsByNextTokenRequest();
				$this->request->setSellerId(MERCHANT_ID);
				$this->request->setNextToken($next_token);
				$this->invokeListOrderItems($this->service, $this->request, 'next_token');
			}

			else
			{
				$this->amazon_mws->show_ouput(TRUE);
			}

		}
		catch (MarketplaceWebServiceOrders_Exception $ex)
		{
			$this->amazon_mws->format_error($ex->getXML());
			$this->amazon_mws->show_ouput(FALSE);
		}
	}
}